<?php

namespace App\Admin\Forms\Voter;

use App\Models\User\WxUser;
use App\Models\Voter\WxVoter;
use App\Models\Voter\WxVoterPlayer;
use App\Models\Voter\WxVoterPlayerBallot;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class VoterNoticeForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * 处理表单请求.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $voter_id = $input['id'];
        $title = $input['title'];
        $content = $input['content'];
        $object = $input['object'];

        if(!in_array($object, [1,2,3])){
            return $this->response()->error('参数错误');
        }

        if(_empty_($title) || _empty_($voter_id) || _empty_($content)){
            return $this->response()->error('参数错误');
        }

        $voter= WxVoter::find($voter_id);
        if($object == 1){
            UserUtils::add_user_notice(8001, $voter->user_id,$title,$content,100);
            return $this->response()
                ->success('发送成功.')
                ->refresh();
        }else if($object == 2){
            $players = WxVoterPlayer::where('voter_id', $voter_id)->where('status', 1)->get();
            if($players){
                $players->map(function ($v) use ($title, $content){
                    UserUtils::add_user_notice(8001, $v->user_id,$title,$content,100);
                });
                return $this->response()
                    ->success('发送'.count($players).'人成功.')
                    ->refresh();
            }
        }else if($object == 3){
            $array = WxVoterPlayerBallot::where('voter_id', $voter_id)->distinct()->pluck('user_id')->toArray();
            $array = array_unique($array);
            if($array){
                foreach ($array as $user_id){
                    UserUtils::add_user_notice(8001, $user_id,$title,$content,100);
                }
            }
            return $this->response()
                ->success('已发送'.count($array).'人成功.')
                ->refresh();
        }
    }

    /**
     * 构建表单.
     */
    public function form()
    {
        $voter_id = $this->payload["id"];
        $voter = WxVoter::find($voter_id);
        $this->hidden('id')->value($voter_id);

        $this->html(function () {
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">当你想给 选票创建者，选手，参与投票的人 发送系统通知时，可以使用这里。<br/>场景举例说明：
<br/>1、创建选票审核失败，且需要给出原因<br/>2、选票已结束，奖励发放 等等</div>';
        }, '');
        $this->radio('object', '通知对象')->options([1=>'选票创建者', 2=>'报名选手', 3=>'参与投票的用户'])->default(1);
        $this->text('title', '通知标题')->default('');
        $this->textarea('content', '通知内容')->help('带有代码是为了可以被点击跳转')->default('"<a href="/pagesV/voter/detail/detail?id='.$voter->id.'">'.$voter->title.'</a>"选票活动');
    }
}
